package com.example.demo.controller;


import ch.qos.logback.classic.Logger;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.DAO.PageResult;
import com.example.demo.Utils.JwtUtils;
import com.example.demo.common.BatchCategorizeRequest;
import com.example.demo.common.Result;
import com.example.demo.entity.Dish;
import com.example.demo.service.DishService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.demo.common.Result.error;

@RestController
@RequestMapping("/dishes")
public class DishController {
    private Class<com.example.demo.controller.DishController> DishController = com.example.demo.controller.DishController.class;
    ch.qos.logback.classic.Logger logger = (Logger) LoggerFactory.getLogger(DishController);

    @Autowired
    private DishService dishService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/add")
    public boolean addDish(@RequestHeader("Authorization") String token, @RequestBody Dish dish) {
        if (!jwtUtils.validateToken(token)) {
            throw new RuntimeException("Invalid token");
        }
        if (!StringUtils.hasText(dish.getCategory())) {
            dish.setCategory("其他");
        }
        dish.setCategorizedAt(LocalDateTime.now());
        // 可以根据实际需求，判断用户是否有权限创建菜品
        return dishService.save(dish);
    }

    @GetMapping("/getall")
    public List<Dish> getAllDishes(@RequestHeader("Authorization") String token) {
        if (!jwtUtils.validateToken(token)) {
            throw new RuntimeException("Invalid token");
        }
        // 这里可以根据权限判断返回所有菜品还是用户所属餐厅的菜品
        return dishService.list();
    }

    // 后端 DishController 新增日期过滤
    @GetMapping
    public PageResult<Dish> getAllDishes(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "100") int size,
            @RequestParam(required = false) String selectedDate,
            @RequestParam(required = false) String searchType,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) List<Integer> restaurantIds,
            @RequestParam(required = false) List<Integer> departmentIds) {
        logger.info("获取所有菜品，页码：{}，每页大小：{}，日期：{}，搜索类型：{}，关键字：{}",
                page, size, selectedDate, searchType, keyword);

        QueryWrapper<Dish> query = new QueryWrapper<>();

        // 日期过滤
        if (StringUtils.hasText(selectedDate)) {
            LocalDate date = LocalDate.parse(selectedDate);
            query.apply("DATE(categorized_at) = {0}", date);
        }

        // 餐厅ID过滤
        if (restaurantIds != null && !restaurantIds.isEmpty()) {
            query.in("restaurant_id", restaurantIds);
        }

        // 部门ID过滤
        if (departmentIds != null && !departmentIds.isEmpty()) {
            query.in("department_id", departmentIds);
        }

        // 菜品名称模糊查询
        if (StringUtils.hasText(keyword) && "dish".equals(searchType)) {
            query.like("name", keyword);
        }

        Page<Dish> pageInfo = new Page<>(page, size);
        return PageResult.success(dishService.page(pageInfo, query));
    }

    @GetMapping("/by-restaurant")
    public PageResult<Dish> getDishesByRestaurant(
            @RequestHeader("Authorization") String token,
            @RequestParam Integer restaurantId,
            @RequestParam(required = false) Integer departmentId,
            @RequestParam(required = false) String selectedDate, // 添加日期参数
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        // 添加参数校验
        if (restaurantId == null) {
            return PageResult.error("restaurantId不能为空");
        }

        Page<Dish> pageInfo = new Page<>(page, size);
        QueryWrapper<Dish> query = new QueryWrapper<>();
        query.eq("restaurant_id", restaurantId);

        if (departmentId != null) {
            query.eq("department_id", departmentId);
        }

        // 添加日期过滤逻辑
        if (StringUtils.hasText(selectedDate)) {
            LocalDate date = LocalDate.parse(selectedDate);
            query.apply("DATE(categorized_at) = {0}", date);
        }

        return PageResult.success(dishService.page(pageInfo, query));
    }

    // 添加在DishController类中

    // 在DishController类中添加
    @GetMapping("/categories")
    public Result<List<String>> getCategories(@RequestHeader("Authorization") String token) {
        // 权限验证
        if (!jwtUtils.validateToken(token)) {
            return (Result<List<String>>) Result.error(401, "无效的Token");
        }
        // 构建查询条件
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT category"); // 获取唯一分类
        queryWrapper.isNotNull("category");
        queryWrapper.ne("category", "");

        // 执行查询
        List<Dish> dishes = dishService.list(queryWrapper);

        // 提取并处理分类数据
        List<String> categories = dishes.stream()
                .map(Dish::getCategory)
                .filter(category -> !StringUtils.isEmpty(category))
                .collect(Collectors.toList());

        return Result.success(categories);
    }

    // 修改批量分类接口
    @PutMapping("/batch-categorize")
    public Result<?> batchCategorize(
            @RequestHeader("Authorization") String token,
            @RequestBody BatchCategorizeRequest request) {

        // 添加权限验证
        if (!jwtUtils.validateToken(token)) {
            return error(401, "无效的Token");
        }

        List<Dish> updateList = request.getDishIds().stream()
                .map(id -> {
                            Dish dish = new Dish();
                            dish.setId(id);
                            dish.setCategory(request.getCategory());
                            dish.setCategorizedAt(LocalDateTime.now());
                            return dish;})
                .collect(Collectors.toList());

        return dishService.updateBatchById(updateList) ?
                Result.success(null) : error(500, "更新失败");
    }

    // Excel导出接口
    @GetMapping("/export")
    public void exportDishes(
            @RequestParam String category,
            HttpServletResponse response
    ) throws IOException {
        // 处理默认分类查询
        if ("其他".equals(category)) {
            category = ""; // 查询空分类的数据
        }

        List<Dish> dishes = dishService.list(
                new QueryWrapper<Dish>()
                        .eq(StringUtils.hasText(category), "category", category)
                        .or()
                        .isNull("category")
        );

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(category);

        // 创建表头
        HSSFRow headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("菜品名称");
        headerRow.createCell(1).setCellValue("分类");
        headerRow.createCell(2).setCellValue("生成时间");

        // 填充数据（空数据时只导出表头）
        if (!dishes.isEmpty()) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            int rowNum = 1;
            for (Dish dish : dishes) {
                HSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(dish.getName());
                row.createCell(1).setCellValue(dish.getCategory() != null ? dish.getCategory() : "其他");
                row.createCell(2).setCellValue(dish.getCategorizedAt().format(formatter));
            }
        }

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        String fileName = URLEncoder.encode(
                ("其他".equals(category) ? "未分类" : category) + "_" + LocalDate.now() + ".xls",
                "UTF-8"
        );
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        workbook.write(response.getOutputStream());
        workbook.close();
    }
    @PutMapping("/{id}")
    public Result<?> updateDish(
//            @RequestHeader("Authorization") String token,
            @PathVariable Integer id,
            @RequestBody Dish dish) {

//        if (!jwtUtils.validateToken(token)) {
//            return Result.error(401, "无效的Token");
//        }
        logger.info("updateDish");

        dish.setCategorizedAt(LocalDateTime.now());
        return dishService.updateById(dish)
                ? Result.success()
                : Result.error(400,"更新失败");
    }
    // 添加删除接口
    @DeleteMapping("/{id}")
    public Result<?> deleteDish(
            @RequestHeader("Authorization") String token,
            @PathVariable Integer id) {

        if (!jwtUtils.validateToken(token)) {
            return Result.error(401, "无效的Token");
        }

        return dishService.removeById(id)
                ? Result.success()
                : Result.error(500, "删除失败");
    }
    // 按照购物清单格式导出所选菜品
    @GetMapping("/export-selected")
    public void exportSelectedDishes(
           @RequestHeader("Authorization") String authHeader,
            @RequestParam List<Integer> ids,
            HttpServletResponse response) throws IOException {

        // 增强Token验证
        String token = authHeader.replace("Bearer ", "").trim();
        if (!jwtUtils.validateToken(token)) {
            logger.error("导出操作Token验证失败: {}", token);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的Token");
            return;
        }

        logger.info("token",token);
        logger.info("ids",ids);
        logger.info("response",response.toString());
        // 添加空值校验
        if (ids == null || ids.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "请选择要导出的菜品");
            return;
        }

        List<Dish> dishes = dishService.listByIds(ids);
        logger.info("导出所选菜品数量: {}", dishes.size());
        exportAsOrderSheet(dishes, "selected_order", response);
        logger.info("response",response.toString());

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=order.xls");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");


    }

    // 按照购物清单格式按日期导出
    @GetMapping("/export-by-date")
    public void exportDishesByDate(
//            @RequestHeader("Authorization") String token,
            @RequestParam String date,
            HttpServletResponse response) throws IOException {
//        logger.info("response",response.toString());
//
//        if (!jwtUtils.validateToken(token)) {
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的Token");
//            return;
//        }
//        logger.info("token",token);
        LocalDate filterDate = LocalDate.parse(date);
        QueryWrapper<Dish> query = new QueryWrapper<>();
        query.apply("DATE(categorized_at) = {0}", filterDate);
//        logger.info("query",query.toString());
        List<Dish> dishes = dishService.list(query);
//        logger.info("导出日期: {} 的菜品数量: {}", date, dishes.size());
//
//        logger.info("dishes",dishes);
        exportAsOrderSheet(dishes, "order_" + date, response);
    }

    // 按照图片中的购物清单格式导出

    private void exportAsOrderSheet(
            List<Dish> dishes,
            String fileNamePrefix,
            HttpServletResponse response) throws IOException {

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("销售单");

        // 设置列宽
        sheet.setColumnWidth(0, 15 * 256);  // 产品编号
        sheet.setColumnWidth(1, 20 * 256); // 产品名称
        sheet.setColumnWidth(2, 10 * 256); // 规格
        sheet.setColumnWidth(3, 8 * 256);  // 单位
        sheet.setColumnWidth(4, 8 * 256);  // 数量
        sheet.setColumnWidth(5, 8 * 256);  // 单价
        sheet.setColumnWidth(6, 10 * 256); // 金额
        sheet.setColumnWidth(7, 15 * 256); // 备注
        sheet.setColumnWidth(8, 15 * 256); // 分类

        // 1. 添加公司信息（合并单元格）
        HSSFRow companyRow = sheet.createRow(0);
        companyRow.createCell(0).setCellValue("");
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));

        // 2. 添加销售单标题（合并单元格）
        HSSFRow titleRow = sheet.createRow(1);
        titleRow.createCell(0).setCellValue("销售单");
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 8));

        // 3. 添加订单信息行1
        HSSFRow infoRow1 = sheet.createRow(2);
        infoRow1.createCell(0).setCellValue("NO.:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")));
        infoRow1.createCell(4).setCellValue("客户名称：");
        infoRow1.createCell(7).setCellValue("销售日期：" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/M/d")));

        // 4. 添加订单信息行2
        HSSFRow infoRow2 = sheet.createRow(3);
        infoRow2.createCell(0).setCellValue("订单号码：");
        infoRow2.createCell(4).setCellValue("客户地址：");
        infoRow2.createCell(7).setCellValue("送货车号：");

        // 5. 添加表头
        HSSFRow headerRow = sheet.createRow(5);
        String[] headers = {"产品编号", "产品名称", "规格", "单位", "数量", "单价", "金额", "备注", "分类"};
        for (int i = 0; i < headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
        }

        // 6. 填充菜品数据
        int rowNum = 6;
        double totalAmount = 0;
        for (Dish dish : dishes) {
            HSSFRow row = sheet.createRow(rowNum++);
            //double amount = dish.getPrice() * dish.getQuantity();
            //totalAmount += amount;

            row.createCell(0).setCellValue(dish.getId()); // 产品编号
            row.createCell(1).setCellValue(dish.getName()); // 产品名称
            row.createCell(2).setCellValue(""); // 规格（留空）
            row.createCell(3).setCellValue("斤"); // 单位（默认为斤）
            row.createCell(4).setCellValue(dish.getQuantity()); // 数量
            row.createCell(5).setCellValue(dish.getPrice().doubleValue()); // 处理BigDecimal
            //row.createCell(6).setCellValue(amount); // 金额
            row.createCell(7).setCellValue(""); // 备注（留空）
            row.createCell(8).setCellValue(dish.getCategory() != null ? dish.getCategory() : "其他"); // 分类
        }

        // 7. 添加总计行（合并单元格）
        HSSFRow totalRow = sheet.createRow(rowNum++);
        totalRow.createCell(0).setCellValue("总计金额：");
        totalRow.createCell(1).setCellValue(totalAmount);
        sheet.addMergedRegion(new CellRangeAddress(rowNum-1, rowNum-1, 1, 8));

        // 8. 添加签字行（合并单元格）
        HSSFRow signRow1 = sheet.createRow(rowNum+1);
        signRow1.createCell(0).setCellValue("经手人：________________");
        signRow1.createCell(4).setCellValue("收货单位及经手人：________________");
        sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, 0, 3));
        sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, 4, 8));

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        String fileName = URLEncoder.encode(fileNamePrefix + ".xls", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        workbook.write(response.getOutputStream());
        workbook.close();
    }

    // Helper method for Excel export
    @GetMapping("/export-all")
    private void exportToExcel(List<Dish> dishes, String fileNamePrefix, HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("菜品数据");

        // Create header row
        HSSFRow headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("菜品名称");
        headerRow.createCell(1).setCellValue("分类");
        headerRow.createCell(2).setCellValue("价格");
        headerRow.createCell(3).setCellValue("数量");
        headerRow.createCell(4).setCellValue("餐厅");
        headerRow.createCell(5).setCellValue("部门");
        headerRow.createCell(6).setCellValue("创建时间");

        // Fill data
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        int rowNum = 1;
        for (Dish dish : dishes) {
            HSSFRow row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(dish.getName());
            row.createCell(1).setCellValue(dish.getCategory() != null ? dish.getCategory() : "其他");
            row.createCell(2).setCellValue((RichTextString) dish.getPrice());
            row.createCell(3).setCellValue(dish.getQuantity());
            row.createCell(4).setCellValue(dish.getRestaurantId().toString());
            row.createCell(5).setCellValue(dish.getDepartmentId().toString());
            row.createCell(6).setCellValue(dish.getCategorizedAt().format(formatter));
        }

        // Set response headers
        response.setContentType("application/vnd.ms-excel");
        String fileName = URLEncoder.encode(fileNamePrefix + "_" + LocalDate.now() + ".xls", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        workbook.write(response.getOutputStream());
        workbook.close();
    }
}